package com.fms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fms.entity.*;
import com.fms.mapper.*;
import com.fms.result.ResultData;
import com.fms.service.ProcurementService;
import com.fms.vo.InboundVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ProcurementServiceImpl extends ServiceImpl<ProcurementMapper, Procurement> implements ProcurementService {
    private final ProcurementMapper procurementMapper;

    private final ProcurementHistorymapper procurementHistorymapper;

    private final SysUserMapper sysUserMapper;

    private final SysDeptMapper sysDeptMapper;

    private final WarehouseBoardMapper warehouseBoardMapper;

    private final WarehouseHardwareMapper warehouseHardwareMapper;

    //获取采购单
    @Override
    public ResultData getProcurements() {
        LambdaQueryWrapper<Procurement> procurementWrapper = new LambdaQueryWrapper<>();
        List<Procurement> procurements = procurementMapper.selectList(procurementWrapper);
        for (Procurement procurement : procurements){
            LambdaQueryWrapper<ProcurementHistory> historyWrapper = new LambdaQueryWrapper<>();
            historyWrapper.eq(ProcurementHistory::getProcurementId, procurement.getId());
            List<ProcurementHistory> procurementHistories = procurementHistorymapper.selectList(historyWrapper);
            procurement.setProcurementHistories(procurementHistories);
        }
        return ResultData.success(procurements);
    }

    //获取入库单信息
    @Override
    public ResultData getInbounds() {
        List<InboundVo> inboundVos = new ArrayList<>();
        LambdaQueryWrapper<Procurement> procurementWrapper = new LambdaQueryWrapper<>();
        procurementWrapper.eq(Procurement::getWarehousing, 1);
        List<Procurement> procurements = procurementMapper.selectList(procurementWrapper);
        for (Procurement procurement : procurements){
                InboundVo inboundVo = new InboundVo();
                inboundVo.setProcurementId(procurement.getProcurementId()).setDetail(procurement.getDetail()).setMaterialType(procurement.getMaterialType())
                        .setStatus(procurement.getWarehousingInfo()).setUpdateDate(procurement.getUpdateDate());
                inboundVos.add(inboundVo);
        }
        return ResultData.success(inboundVos);
    }

    //新增或修改板子采购单
    @Override
    public ResultData addOrEditBoardProcurement(Procurement procurement) {
        procurement.setStatusInfo("新建");
        procurement.setWarehousing(0);
        procurement.setDetail(procurement.getBoardType()+"-"+procurement.getBoardColor()+"-"+procurement.getBoardBase()+"-"+procurement.getBoardSpecs()+" | 数量:"+procurement.getBoardAmount());
        ProcurementHistory procurementHistory = new ProcurementHistory();
        if(procurement.getId() == null) {
            procurement.setStatus(1).setMaterialType("板子");
            procurementMapper.insert(procurement);
            LambdaQueryWrapper<Procurement> procurementWrapper = new LambdaQueryWrapper<Procurement>();
            procurementWrapper.eq(Procurement::getMaterialType, procurement.getMaterialType()).eq(Procurement::getDetail, procurement.getDetail());
            //采购单Id
            Long procurementId = procurementMapper.selectOne(procurementWrapper).getId();
            SysUser sysUser = sysUserMapper.selectById(procurement.getCreator());
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            procurementHistory.setProcurementId(procurementId).setOperate(1).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("更新采购单信息");
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("新增采购单成功");
        }else{
            SysUser sysUser = sysUserMapper.selectById(procurement.getCreator());
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            Long procurementId = procurement.getId();
            LambdaQueryWrapper<ProcurementHistory> historyWrapper = new LambdaQueryWrapper<>();
            historyWrapper.eq(ProcurementHistory::getProcurementId,procurementId).eq(ProcurementHistory::getBrief,"更新采购单信息").eq(ProcurementHistory::getOperator,sysUser.getRealName()+"("+sysDept.getName()+")");
            procurementHistory.setProcurementId(procurementId).setOperate(1).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("更新采购单信息");
            procurementHistorymapper.delete(historyWrapper);
            procurementHistorymapper.insert(procurementHistory);
            procurementMapper.updateById(procurement);
            return ResultData.success("更新采购单成功");
        }
    }

    //新增或修改五金采购单
    @Override
    public ResultData addOrEditHardwareProcurement(Procurement procurement) {
        procurement.setStatusInfo("新建");
        procurement.setWarehousing(0);
        procurement.setDetail(procurement.getHardwareType()+"-"+procurement.getHardwareSpecs()+"-"+procurement.getHardwareBrand()+"-"+procurement.getHardwareSpecial()+" | 数量:"+procurement.getHardwareAmount());
        ProcurementHistory procurementHistory = new ProcurementHistory();
        if(procurement.getId() == null) {
            procurement.setStatus(1).setMaterialType("五金");
            procurementMapper.insert(procurement);
            LambdaQueryWrapper<Procurement> procurementWrapper = new LambdaQueryWrapper<Procurement>();
            procurementWrapper.eq(Procurement::getMaterialType, procurement.getMaterialType()).eq(Procurement::getDetail, procurement.getDetail());
            //采购单Id
            Long procurementId = procurementMapper.selectOne(procurementWrapper).getId();
            SysUser sysUser = sysUserMapper.selectById(procurement.getCreator());
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            procurementHistory.setProcurementId(procurementId).setOperate(1).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("更新采购单信息");
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("新增采购单成功");
        }else{
            procurementMapper.updateById(procurement);
            SysUser sysUser = sysUserMapper.selectById(procurement.getCreator());
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            Long procurementId = procurement.getId();
            LambdaQueryWrapper<ProcurementHistory> historyWrapper = new LambdaQueryWrapper<>();
            historyWrapper.eq(ProcurementHistory::getProcurementId,procurementId).eq(ProcurementHistory::getBrief,"更新采购单信息").eq(ProcurementHistory::getOperator,sysUser.getRealName()+"("+sysDept.getName()+")");
            procurementHistory.setProcurementId(procurementId).setOperate(1).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("更新采购单信息");
            procurementHistorymapper.delete(historyWrapper);
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("更新采购单成功");
        }
    }

    //删除采购单
    @Override
    public ResultData deleteProcurementById(Long id) {
        procurementMapper.deleteById(id);
        LambdaQueryWrapper<ProcurementHistory> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(ProcurementHistory::getProcurementId, id);
        procurementHistorymapper.delete(historyWrapper);
        return ResultData.success("删除采购单成功");
    }

    //流转采购单
    @Override
    public ResultData transferProcurement(Procurement procurement) {
        Integer originStatus = procurement.getStatus();
        procurement.setStatus(originStatus+1);
        ProcurementHistory procurementHistory =  new ProcurementHistory();
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUsername, procurement.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
        procurement.setUpdateDate(null).setUpdater(sysUser.getId());
        if (originStatus == 1){
            procurement.setStatusInfo("等待审批");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("提交采购单申请");
        }
        else if (originStatus == 2){
            procurement.setStatusInfo("等待最终审批");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("审批采购单：通过");
            procurementMapper.updateById(procurement);
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("采购单审批成功");
        }
        else if (originStatus == 3){
            procurement.setStatusInfo("审批通过，等待财务");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("审批采购单：通过");
            procurementMapper.updateById(procurement);
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("采购单审批成功");
        }
        else if (originStatus == 4){
            procurement.setStatusInfo("等待收货入库");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("提交支付信息");
        }
        else if (originStatus == 5){
            procurement.setStatusInfo("等待财务确认");
            procurement.setWarehousingInfo("等待确认");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("提交入库单信息");
        }
        else if (originStatus == 6){
            procurement.setStatusInfo("等待经理确认");
            procurement.setWarehousingInfo("等待确认");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("确认采购单信息");
            procurementMapper.updateById(procurement);
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("采购单信息确认成功");
        }
        else if (originStatus == 7){
            procurement.setStatusInfo("等待最终确认");
            procurement.setWarehousingInfo("等待确认");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("确认采购单信息");
            procurementMapper.updateById(procurement);
            procurementHistorymapper.insert(procurementHistory);
            return ResultData.success("采购单信息确认成功");
        }
        else if (originStatus == 8){
            procurement.setStatus(0);
            procurement.setStatusInfo("已完成");
            procurement.setWarehousingInfo("已完成");
            procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("确认采购单信息");
            procurementMapper.updateById(procurement);
            procurementHistorymapper.insert(procurementHistory);

            //材料入库
            if ("板子".equals(procurement.getMaterialType())){
                LambdaQueryWrapper<WarehouseBoard> boardWrapper = new LambdaQueryWrapper<WarehouseBoard>();
                boardWrapper.eq(WarehouseBoard::getBoardBase, procurement.getBoardBase()).eq(WarehouseBoard::getBoardColor, procurement.getBoardColor())
                        .eq(WarehouseBoard::getBoardType, procurement.getBoardType()).eq(WarehouseBoard::getBoardSpecs, procurement.getBoardSpecs());
                WarehouseBoard board = warehouseBoardMapper.selectOne(boardWrapper);
                if (board != null){
                    warehouseBoardMapper.rollbackAmount(procurement.getBoardAmount(),board.getId());
                }else {
                    WarehouseBoard boards = new WarehouseBoard();
                    boards.setBoardBase(procurement.getBoardBase()).setBoardColor(procurement.getBoardColor()).setBoardSpecs(procurement.getBoardSpecs())
                            .setBoardType(procurement.getBoardType()).setBoardAmount(procurement.getBoardAmount())
                            .setBoardTitle(procurement.getBoardType()+" "+procurement.getBoardColor()+" "+procurement.getBoardBase());
                    warehouseBoardMapper.insert(boards);
                }
            }else{
                LambdaQueryWrapper<WarehouseHardware> hardwareWrapper = new LambdaQueryWrapper<WarehouseHardware>();
                hardwareWrapper.eq(WarehouseHardware::getHardwareType, procurement.getHardwareType()).eq(WarehouseHardware::getHardwareSpecs, procurement.getHardwareSpecs())
                        .eq(WarehouseHardware::getHardwareBrand, procurement.getHardwareBrand()).eq(WarehouseHardware::getHardwareSpecial, procurement.getHardwareSpecial());
                WarehouseHardware hardware = warehouseHardwareMapper.selectOne(hardwareWrapper);
                if(hardware != null){
                    warehouseHardwareMapper.rollbackAmount(procurement.getHardwareAmount(), hardware.getId());
                }else {
                    WarehouseHardware hWare = new WarehouseHardware();
                    hWare.setHardwareType(procurement.getHardwareType()).setHardwareSpecs(procurement.getHardwareSpecs())
                            .setHardwareBrand(procurement.getHardwareBrand()).setHardwareSpecial(procurement.getHardwareSpecial())
                            .setHardwareAmount(procurement.getHardwareAmount()).setHardwareTitle(procurement.getHardwareType()+" "+procurement.getHardwareSpecs()+" "+procurement.getHardwareBrand());
                    warehouseHardwareMapper.insert(hWare);
                }
            }
            return ResultData.success("采购单信息确认成功");
        }
        procurementMapper.updateById(procurement);
        procurementHistorymapper.insert(procurementHistory);
        return ResultData.success("采购单流程转交成功");
    }

    //否决订单
    @Override
    public ResultData denyProcurement(Procurement procurement) {
        procurement.setStatus(-1);
        ProcurementHistory procurementHistory =  new ProcurementHistory();
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUsername, procurement.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
        procurement.setUpdateDate(null).setUpdater(sysUser.getId());
        procurement.setStatusInfo("已被否决");
        procurementHistory.setProcurementId(procurement.getId()).setOperate(0).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("审批采购单：否决");
        procurementMapper.updateById(procurement);
        procurementHistorymapper.insert(procurementHistory);
        return ResultData.success("采购单已否决");
    }

    //新增支付信息
    @Override
    public ResultData addPaymentProcurement(Procurement procurement) {
        procurement.setPayDate(procurement.getPayDateD());
        ProcurementHistory procurementHistory =  new ProcurementHistory();
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUsername, procurement.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
        procurement.setUpdateDate(null).setUpdater(sysUser.getId());
        procurement.setStatusInfo("财务支付");
        Long procurementId = procurement.getId();
        LambdaQueryWrapper<ProcurementHistory> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(ProcurementHistory::getProcurementId,procurementId).eq(ProcurementHistory::getBrief,"更新支付信息").eq(ProcurementHistory::getOperator,sysUser.getRealName()+"("+sysDept.getName()+")");
        procurementHistory.setProcurementId(procurement.getId()).setOperate(1).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("更新支付信息");
        procurementHistorymapper.delete(historyWrapper);
        procurementMapper.updateById(procurement);
        procurementHistorymapper.insert(procurementHistory);
        return ResultData.success("支付信息更新成功");
    }

    //新增入库单信息
    @Override
    public ResultData addWarehousingProcurement(Procurement procurement) {
        procurement.setWarehousing(1);
        procurement.setWarehousingInfo("未提交");
        ProcurementHistory procurementHistory =  new ProcurementHistory();
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUsername, procurement.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
        procurement.setUpdateDate(null).setUpdater(sysUser.getId());
        procurement.setStatusInfo("等待入库单提交");
        Long procurementId = procurement.getId();
        LambdaQueryWrapper<ProcurementHistory> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(ProcurementHistory::getProcurementId,procurementId).eq(ProcurementHistory::getBrief,"更新入库单信息").eq(ProcurementHistory::getOperator,sysUser.getRealName()+"("+sysDept.getName()+")");
        procurementHistory.setProcurementId(procurement.getId()).setOperate(1).setOperator(sysUser.getRealName()+"("+sysDept.getName()+")").setBrief("更新入库单信息");
        procurementHistorymapper.delete(historyWrapper);
        procurementMapper.updateById(procurement);
        procurementHistorymapper.insert(procurementHistory);
        return ResultData.success("入库信息更新成功");
    }
}
